# -*- coding: utf-8 -*-
'''
@author: Johnny
@Created on: 2011-6-28
@version: 2011.6.28
@summary: functions related checking server connection, checker(), tryConn()
          and connServ()
'''
import time, subprocess, copy
from selenium import selenium


def checker(host):
    '''
    Start selenium to check whether connection is OK.
    Keyword arguments:
    host -- host and port list
    '''
    flag = False
    try:
        sele = selenium(host[0], host[1], "*chrome", "http://www.google.com.cn/")
        sele.start()
        sele.stop()
        flag = True
    except:
        flag = False
            
    del sele
    return flag


def try_connect(host, rootpath, serverpath, profilepath):
    '''
    Try to connect to selenium server.
    Keyword arguments:
    host -- host and port list
    rootpath -- server bat root path
    serverpath -- selenium server path
    profilepath -- firefox profile path
    '''
    if host[2].find('firefox') >= 0 or host[2].find('*chrome') >= 0:
        serverBat = '\\osim_site\\util\\server.bat '
        psexecBat = '\\osim_site\\util\\psexec.bat '
    else:
        serverBat = '\\osim_site\\util\\server_other.bat '
        psexecBat = '\\osim_site\\util\\psexec_other.bat '
            
    if host[0] == 'localhost':
        command = 'start ' + rootpath + serverBat + str(serverpath) \
            + ' ' + host[1] + ' ' + str(profilepath)
        subprocess.Popen(command, shell = True)
    else:
        command = 'start ' + rootpath + psexecBat + host[0] + ' ' + host[1]
        subprocess.Popen(command, shell = True)


def connect(hosts, rootpath, serverpath, profilepath):
    '''
    Connect to selenium server.
    Keyword arguments:
    host -- host and port list
    rootpath -- server bat root path
    serverpath -- selenium server path
    profilepath -- firefox profile path
    '''
    for i in range(len(hosts)):
        hosts[i] = hosts[i].split(',')
        try_connect(hosts[i], rootpath, serverpath, profilepath)
    
    time.sleep(5)
    
    m_hosts = copy.deepcopy(hosts)
    temp = [] 
       
    for host in m_hosts:
        flag = False
        count = 0
        flag = checker(host)
        while not flag and count<5:
            try_connect(host, rootpath, serverpath, profilepath)
            flag = checker(host)
            time.sleep(1)
            count += 1
        if not flag:
            temp.append(host)
            print "Failed to connect remote host:", host[0], host[1]
    
    for t in temp:
        m_hosts.remove(t)
                      
    return m_hosts
